//
//  WBMainTabBarController.swift
//  weibo
//
//  Created by HanXujie on 2017/4/9.
//  Copyright © 2017年 thinker. All rights reserved.
//

import UIKit

class WBMainTabBarController: UITabBarController {    
    

    
    /// 定时器
    fileprivate var timer: Timer?
    
    deinit {
        // 销毁定时器
        timer?.invalidate()
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildViewController()
        setupComposeButton()
        
        setupTimer()
        
        // 设置代理
        delegate  = self
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        
    }
    
    /// 用户登录通知的监听方法
    ///
    /// - Parameter n: 通知
    @objc fileprivate func userLogin(n:Notification){
        
        print("用户登录通知的监听\(n)")
        
        // 展现登录控制器-通常和navagationController连用方便返回
        let nav = UINavigationController(rootViewController: WBOauthViewController())
        
        present(nav, animated: true, completion:nil)
        
        
    }

    
    // MARK: - 撰写按钮的监听方法
    // FIXME:撰写按钮监听方法实现
    /*
     @objc:允许函数在运行时通过OC的消息机制来访问
     fileprivate：保证函数是私有的
     
     */
   @objc fileprivate func composeState() -> () {
        
    
    // 测试方向旋转
    let vc = UIViewController()
    vc.view.backgroundColor = UIColor.cz_random()
    let nav = UINavigationController(rootViewController: vc)
    present(nav, animated: true, completion: nil)
    
        
    }
    
    // 撰写按钮
    fileprivate lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button");

}


// MARK: - UITabBarControllerDelegate
extension WBMainTabBarController: UITabBarControllerDelegate{
    
    
    /// 将要选择TabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController description
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        print("将要切换到\(viewController)")
        // 获取控制器在数组中的索引
        let idx = childViewControllers.index(of: viewController)

        // 判断当前索引是首页，同时index也是首页，达到点击其他页面后返回首页不刷新
        if selectedIndex == 0 && idx == selectedIndex {
            // 让表格滚动到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            vc.tablewView?.setContentOffset(CGPoint.init(x: 0, y: -64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                 vc.loadData()
            })
           
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }

}






// MARK: - timer相关方法
extension WBMainTabBarController{
    
    func setupTimer() {

        if #available(iOS 10.0, *) {
            timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true, block: { (timer) in
                 // 如果token没有值那么不检测微博的更新
                if !WBNetworkManager.shared.userLogin {
                    return
                }
                // 设置badgeNumber
                WBNetworkManager.shared.unreadCount(completion: { (count) in
                    print("检测到\(count)条微博")
                    self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
                    UIApplication.shared.applicationIconBadgeNumber = count
                })
            })
        } else {
            // Fallback on earlier versions
            timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(performTimerMethed), userInfo: nil, repeats: true)
        }
        
    }
    
    /// iOS10以前调用此方法
    @objc fileprivate func performTimerMethed() {
        // 如果token没有值那么不检测微博的更新
        if !WBNetworkManager.shared.userLogin {
            return
        }
        
        print("旧版本方法的调用")
        WBNetworkManager.shared.unreadCount(completion: { (count) in
            
            print("检测到\(count)条微博")
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            UIApplication.shared.applicationIconBadgeNumber = count
        })
    }
    
}


/*
 extension类似于OC中的分类，在swift中还可以用来切分代码块
 可以把相近功能的函数放在同一个extension中，便于代码维护
 注意：和OC的分类是一样的，extension中不能定义属性
 
 */

// MARK: - 设置界面
extension WBMainTabBarController{
    
    /// 设置撰写按钮
    fileprivate func setupComposeButton(){
        tabBar.addSubview(composeButton)
        // 设置按钮的位置
        let count = CGFloat(childViewControllers.count)
        // 让按钮的库宽度变大盖住容错点，防止误点
        let w = tabBar.bounds.width / count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        // 给按钮添加监听
        composeButton.addTarget(self, action: #selector(composeState), for: .touchUpInside)
    }
    
    /*
     portrait:竖屏，肖像
     landscape:横屏，风景画
     
     使用代码来控制设备的方向，好处是可以在需要横屏的时候单独的处理
     设置支持的方向之后，当前的控制器以及自控制器都会遵守这个方向
     如果是视频播放，通常是modal展现的
     
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    

    
    
    /// 设置所有的子控制器
    fileprivate func setupChildViewController(){
        
        
        
        // 获取沙盒
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        // 拼接路径
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        // 加载数据
        var data = NSData(contentsOfFile: jsonPath)
        // 判断如果本地沙盒没有数据就加载默认数据
        if data == nil {
            let path = Bundle.main.path(forResource: "main", ofType: "json")
            data = NSData(contentsOfFile: path!)
            
        }
        
        // 从bundle加载配置的json
        guard let arry = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as?[[String :Any]]
            else {
            return
        }
        
        
        
        
        
//        let arry :[[String :Any]] = [
//        
//            ["clsName": "WBHomeViewController","title":"首页","imageName":"home","visitorInfo" : ["imageName" : "","message" : "关注一些人，回这里看看有什么惊喜"]],
//            
//            ["clsName": "WBMessageViewController","title":"消息","imageName":"message_center","visitorInfo" : ["imageName" : "visitordiscover_image_message","message" : "登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
//            
//            // 设置一个空的控制器来做中间撰写按钮的占位
//            [:] as Dictionary,
//            
//            ["clsName": "WBDiscoverViewController","title":"发现","imageName":"discover","visitorInfo" : ["imageName" : "visitordiscover_image_message","message" : "登录后，最新、最热微博尽在掌握，不在会与实事擦肩而过"]],
//            
//            ["clsName": "WBProfileViewController","title":"我","imageName":"profile","visitorInfo" : ["imageName" : "visitordiscover_image_profile","message" : "登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]]
//        ]
//        
        // 测试数据格式是否正确
//        (arry as NSArray).write(toFile: "/Users/apple/Desktop/info.plist", atomically: true)
        
//        let url = NSURL(fileURLWithPath: "/Users/apple/Desktop/info.json")
        
        // 将界面信息写成json
        // FIXME:- try的使用
//        do {
//            let data = try JSONSerialization.data(withJSONObject: arry, options: [.prettyPrinted])
//            try data.write(to: url as URL)
//            
//        } catch {
//            
//            print("错误")
//            
//        }
        
        
        // 遍历数组，循环创建控制器
        var arryM = [UIViewController]()
        for dict in arry! {
            arryM.append(controller(dic: dict))
        }
        // 设置tabBar子控制器
        viewControllers = arryM
    }
    
    
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dic: 信息字典[clsName,title,imageName]
    /// - Returns: 子控制器
    fileprivate func controller(dic:[String : Any])->UIViewController{
        
        guard let clsName = dic["clsName"] as? String,
            let title = dic["title"] as? String,
            let imageName = dic["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
        let visitorDict = dic["visitorInfo"] as? [String :String]
            else {
             return UIViewController()
        }
        // 创建视图
        let vc = cls.init()
        
        vc.title = title
        
        // 设置访客视图信息字典
        vc.vistorInfoDict = visitorDict
        
        // 设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        // 设置tabbar的标题颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .selected)
        // 设置字体，系统默认是12号字体，如果要修改需要设置Normal的字体大小
//        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName :UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue:0))
        
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
        
   }
    
    
    
    
    
}


















